class CommentsController < ApplicationController
  before_filter :comments_management_access
  before_filter :get_document                     , :except => :destroy
  before_filter :document_should_be_allow_comments, :except => :destroy

  def new
    @comment = Comment.new
  end

  def create
    @comment = @document.comments.new(params[:comment])
    @comment.user = current_user
    @success = @comment.save
    @count = @document.comments.count
  end

  def destroy
    @comment = Comment.find(params[:id])
    if comment_must_be_owned_user @comment
      @success = @comment.destroy
      @count = @comment.document.comments.count
    end
  end

  protected
    def get_document
      @document = Document.find(params[:document_id])
    end

    def comments_management_access
      check_access :comment
    end

    def document_should_be_allow_comments
      unless @document.comments_allowed?
        render :text => t('comments.document_comments_not_allowed') and return
      end
    end

    def comment_must_be_owned_user(comment)
      comment.user == current_user
    end
end
